import base64
from enum import Enum
import httpx
import io
import json
import logging
import os
from PIL import Image
from datetime import datetime


class TASK_STATUS(Enum):
    CREATED = 1
    PROCESSING = 2
    SUCCESS = 3


def download_file(url, filename):
    log = setup_logger('common')
    current_file_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_file_path)
    project_root_path = os.path.dirname(current_dir_path)
    project_root_path = os.path.dirname(project_root_path)
    videos_dir = os.path.join(project_root_path, 'videos')
    os.makedirs(videos_dir, exist_ok=True)

    # 设置完整的文件路径
    full_path = os.path.join(videos_dir, filename)
    with httpx.Client() as client:
        response = client.get(url, follow_redirects=True)

        # 检查响应状态码
        if response.status_code == 200:
            # 打开文件并写入内容
            with open(full_path, 'wb') as file:
                file.write(response.content)
            log.info(f"【下载完成】 {url} -> {full_path}")
        else:
            log.error(f"下载失败，状态码：{response.status_code}")


def image_to_base64(image_path):
    image = Image.open(image_path)

    # 将图片转换为字节流
    image_byte_array = io.BytesIO()
    image.save(image_byte_array, format='JPEG')
    image_byte_array = image_byte_array.getvalue()

    # 将字节流编码为Base64字符串
    return base64.b64encode(image_byte_array).decode('utf-8')

async def download_file_async(url, filename):
    log = setup_logger('common')
    async with httpx.AsyncClient() as client:
        response = await client.get(url, follow_redirects=True)

        if response.status_code == 200:
            with open(filename, 'wb') as file:
                file.write(response.content)
            log.info(f"文件已下载并保存为 {filename}")
        else:
            log.info(f"下载失败，状态码：{response.status_code}")


def is_json(data):
    try:
        # 尝试解析 JSON 字符串
        json.loads(data)
        return True
    except TypeError:
        # 解析失败，不是有效的 JSON 字符串
        return False
    except json.JSONDecodeError or TypeError:
        # 解析失败，不是有效的 JSON 字符串
        return False


def task_info_to_file(data):
    current_file_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_file_path)
    project_root_path = os.path.dirname(current_dir_path)
    project_root_path = os.path.dirname(project_root_path)
    tasks_dir = os.path.join(project_root_path, 'tasks')
    os.makedirs(tasks_dir, exist_ok=True)
    full_path = os.path.join(tasks_dir, 'tasks.json')

    if is_json(data):
        with open(full_path, 'w', encoding='utf-8') as file:
            file.write(data)
    else:
        # 将字典转换为 JSON 字符串
        json_str = json.dumps(data, indent=4, ensure_ascii=False)

        # 将 JSON 字符串写入文件
        with open(full_path, 'w', encoding='utf-8') as file:
            file.write(json_str)


def read_task_info_file():
    current_file_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_file_path)
    project_root_path = os.path.dirname(current_dir_path)
    project_root_path = os.path.dirname(project_root_path)
    tasks_dir = os.path.join(project_root_path, 'tasks')

    print(f'tasks_dir:     {tasks_dir}')

    if not os.path.exists(tasks_dir):
        return None
    full_path = os.path.join(tasks_dir, 'tasks.json')
    with open(full_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data


def upsert_task_info(task: dict):
    data = read_task_info_file()
    new_array = []
    exists_data = False
    for old_task_data in data:
        if old_task_data['task_id'] == task['task_id']:
            new_array.append(task)
            exists_data = True
        else:
            new_array.append(old_task_data)
    if not exists_data:
        new_array.append(task)
    task_info_to_file(new_array)


def setup_logger(logger_name):
    # 获取当前日期
    current_file_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_file_path)
    project_root_path = os.path.dirname(current_dir_path)
    project_root_path = os.path.dirname(project_root_path)
    logs_dir = os.path.join(project_root_path, 'logs')

    current_date = datetime.now().strftime('%Y-%m-%d')
    log_filename = f'{current_date}.log'
    log_path = os.path.join(logs_dir, log_filename)

    # 创建日志目录（如果不存在）
    log_dir = os.path.dirname(log_path)
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 创建 logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)  # 设置日志级别

    # 创建文件处理器，将日志写入文件
    file_handler = logging.FileHandler(log_path)
    file_handler.setLevel(logging.DEBUG)

    # 创建控制台处理器，将日志输出到控制台
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    # 创建日志格式
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # 添加处理器到 logger
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger

